import axios from 'axios'
import { BASE_URL, TIME_OUT } from './config'
import useMainStore from '@/stores/modules/main'
import { storeToRefs } from 'pinia'
const mainStore = useMainStore()
const { isLoading } = storeToRefs(mainStore)
class HYRequest {
  constructor(baseURL, timeout = 10000) {
    this.instance = axios.create({ baseURL, timeout })
  }

  request(config) {
    isLoading.value = true
    return new Promise((resolve, reject) => {
      this.instance
        .request(config)
        .then((res) => resolve(res.data))
        .catch((err) => reject(err))
        .finally(() => {
          isLoading.value = false
        })
    })
  }

  get(config) {
    return this.request({ ...config, method: 'get' })
  }

  post(config) {
    return this.request({ ...config, method: 'post' })
  }

  delete(config) {
    return this.request({ ...config, method: 'delete' })
  }

  put(config) {
    return this.request({ ...config, method: 'put' })
  }

  patch(config) {
    return this.request({ ...config, method: 'patch' })
  }

  head(config) {
    return this.request({ ...config, method: 'head' })
  }

  options(config) {
    return this.request({ ...config, method: 'options' })
  }

  // 可选：静态方法处理并发请求
  static all(promises) {
    return axios.all(promises)
  }
}

// 创建 HYRequest 的实例
const hyRequest = new HYRequest(BASE_URL, TIME_OUT)

export default hyRequest
